package io.renren.service.impl;

import io.renren.controller.AbstractController;
import io.renren.dao.*;
import io.renren.entity.*;
import io.renren.service.ActFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;



@Service("actFlowService")
public class ActFlowServiceImpl extends AbstractController implements ActFlowService {
	@Autowired
	private ActFlowDao actFlowDao;
	@Autowired
	private ActHistoryDao actHistoryDao;
	@Autowired
	private ActAssigndtlDao actAssigndtlDao;
	@Autowired
	private SysOfficeDao sysOfficeDao;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private ActSendtoDao actSendtoDao;
	
	@Override
	public ActFlowEntity queryObject(Integer id){
		return actFlowDao.queryObject(id);
	}
	
	@Override
	public List<ActFlowEntity> queryList(Map<String, Object> map){
		return actFlowDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return actFlowDao.queryTotal(map);
	}
	
	@Override
	public void save(ActFlowEntity actFlow){
		actFlowDao.save(actFlow);
	}

	@Override
	public void update(ActFlowEntity actFlow){
		actFlowDao.update(actFlow);
	}
	
	@Override
	public void delete(Integer id){
		actFlowDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		actFlowDao.deleteBatch(ids);
	}


	/*
         level为1取当前部门主管，level为2取上级主管，以此类推
    */
	@Override
	public Map submitFlow(ActAssignEntity actAssign, Object obj,String processName){
		List<ActAssigndtlEntity> actAssigndtlList =actAssigndtlDao.queryListByHead(actAssign.getId());
		Map<String, Object> map=new HashMap<>();
		if(actAssigndtlList==null||actAssigndtlList.size()==0){
			map.put("msg","请在审批配置中配置审批条件！");
			return map;
		}

		List<String> list=new ArrayList<>();
		int k=0;//记录指定个人的次数
		String dept=getUser().getDeptNo();//当前部门
		String deptName=getUser().getDept();//当前部门名称
		String isSupervisor=getUser().getIssupervisor();//申请人是否主管
		SysOfficeEntity office	=sysOfficeDao.queryObject(dept);//当前部门的数据
		for(int i=0;i<actAssigndtlList.size();i++){
			ActAssigndtlEntity pojo=actAssigndtlList.get(i);
			String  type =pojo.getType();
			String username="";
			int level=pojo.getLevel()-k;
			//指定的是主管
			if("0".equals(type)){
				if("0".equals(isSupervisor)){
					//自己是主管,level为1取上级部门，level为2取上上级主管，以此类推
					level++;
				}
				if(level>1){
					String parentId=office.getParentId();//上级部门
					office	=sysOfficeDao.queryObject(parentId);
					dept=office.getId()+"";
					deptName=office.getName();
				}
				//找出对应部门的主管
				List<SysUserEntity> listUser =sysUserDao.queryZgByDeptNo(dept);
				if(listUser==null||listUser.size()==0){
					map.put("msg",deptName+"没有主管，请先配置!");
					return map;
				}
				SysUserEntity user=listUser.get(0);
				username=user.getUsername();//主管姓名

			}else if("1".equals(type)){//指定是个人
				username=pojo.getUsername();
				k++;//如果第一级指定个人，第二级审批指定主管，此时指定的当前主管，而非上级主管

			}
			if(io.renren.utils.StringUtils.isNoneBlank(username)){
				list.add(username);
			}
		}

		Collections.reverse( list);


		int nextIndex=0;
		int len=list.size();
		int piid=(int)((Math.random()*9+1)*100000);
		for (int i=0;i<len;i++){
			ActFlowEntity pojo=new ActFlowEntity();
			pojo.setPiid(piid);
			pojo.setProcessName(processName);
			pojo.setProcessLevel(len-i);
			pojo.setUsername(list.get(i));
			pojo.setNextIndex(nextIndex);
			actFlowDao.save(pojo);
			nextIndex=pojo.getId();
		}
		map.put("piid",piid);
		map.put("nextUser",list.get(len-1));
		map.put("pistatus","1");
		map.put("nextTo",nextIndex);
	/*	Class cls = obj.getClass();
		Field[] fields = cls.getDeclaredFields();
		for (Field fd : fields) {
			fd.setAccessible(true);
			String fname = fd.getName();
			Set<String> set = map.keySet();
			Iterator<String> it = set.iterator();
			while (it.hasNext()){
				String name = it.next();
				if(name.equals(fname))
				{
					Object o = map.get(name);
					try {
						fd.set(obj,o);
					 } catch (IllegalAccessException e) {
						e.printStackTrace();
					 }
					 break;
				}
			}

		}*/
		obj=reflection( obj, map);
		map.put("obj",obj);
		return map;
	}

	@Override
	public Object saveFlow(Map<String, Object> hashMap,Object obj,String result,String processName){
		ActFlowEntity flow =actFlowDao.queryObject(hashMap.get("nextTo").toString());
		ActHistoryEntity pojo=new ActHistoryEntity();
		pojo.setPiid(Integer.valueOf(hashMap.get("piid").toString()));
		pojo.setProcessName(processName);
		pojo.setProcessLevel(flow.getProcessLevel());
		pojo.setUsername(flow.getUsername());
		pojo.setApproveDate(new Date());
		pojo.setResult(result);
		pojo.setRemark(hashMap.get("remark").toString());
		actHistoryDao.save(pojo);
		Map<String, Object> map=new HashMap<>();
		map.put("nextTo",flow.getNextIndex());
//		leave.setNextTo(flow.getNextIndex());
		if(flow.getNextIndex()==0){//等于0是最后一个人审批
			/*leave.setPistatus("0");
			leave.setNextUser("");*/
			map.put("nextUser","");
			map.put("pistatus","0");

		}else{
		/*	leave.setPistatus(String.valueOf(flow.getProcessLevel()+1));
			leave.setNextUser(actFlowDao.queryObject(flow.getNextIndex()).getUsername());*/
			map.put("nextUser",actFlowDao.queryObject(flow.getNextIndex()).getUsername());
			map.put("pistatus",String.valueOf(flow.getProcessLevel()+1));


		}
		//流程审批完或者拒绝获取抄送人
		if(flow.getNextIndex()==0||"reject".equals(result)){
			List<ActSendtoEntity> listActSendto =actSendtoDao.queryObjectByProcess(processName);
			if(listActSendto!=null&&listActSendto.size()>0){
//				leave.setNextUser(listActSendto.get(0).getUsername());
				map.put("nextUser",listActSendto.get(0).getUsername());
			}

		}
		obj=reflection( obj, map);
		flow.setApproveDate(new Date());
		actFlowDao.update(flow);
		return obj;
	}


	Object reflection (Object obj,Map<String, Object> map){
		Class cls = obj.getClass();
		Field[] fields = cls.getDeclaredFields();
		for (Field fd : fields) {
			fd.setAccessible(true);
			String fname = fd.getName();
			Set<String> set = map.keySet();
			Iterator<String> it = set.iterator();
			while (it.hasNext()){
				String name = it.next();
				if(name.equals(fname))
				{
					Object o = map.get(name);
					try {
						fd.set(obj,o);
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
					break;
				}
			}

		}
		return  obj;
	}



}
